package com.skyline.attraction.controller;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.skyline.attraction.model.Ratyable;
import com.skyline.attraction.service.RatyService;
import com.skyline.attraction.type.RatyType;
import com.skyline.base.controller.BaseController;
import com.skyline.base.exception.NotLoginException;
import com.skyline.user.model.User;

@Controller
public class RatyController extends BaseController {
	private static final Log LOGGER = LogFactory.getLog(RatyController.class);
	
	@Autowired
	private RatyService ratyService;
	
	@RequestMapping(value = "/vote", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> vote(@RequestParam("id") Long id, @RequestParam("star") Integer star, @RequestParam("type") RatyType type) {
		try {
			User user = checkAndReturnLoginedUser();
			Long userId = user.getId();
			
			boolean voted = ratyService.hasRaty(id, type, userId);
			if(voted) {
				Map<String, Object> json = toJsonMap(false, "对不起，您已经评分过了，请不要重复评价", true);
				json.put("voted", voted);
				return json;
			}
			
			Ratyable target = ratyService.ratyStar(id, type, userId, star);
			Map<String, Object> json = toJsonMap(true, "评分成功", true);
			json.put("star", target.getStar());
			json.put("votes", target.getVotes());
			return json;
		} catch (NotLoginException e) {
			return toJsonMap(false, "您的登录已超时，请重新登录后再评分", false);
		} catch (Exception e) {
			LOGGER.warn("特色评分失败", e);
			return toJsonMap(false, "对不起，评分失败！", true);
		}
	}
}
